package com.example.agent;

import javassist.*;

import java.lang.instrument.ClassFileTransformer;
import java.security.ProtectionDomain;

public class ApiTransformer implements ClassFileTransformer {
    @Override
    public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
                            ProtectionDomain protectionDomain, byte[] classfileBuffer) {
        if (className.contains("controller")) { // 只拦截 Controller
            try {
                ClassPool cp = ClassPool.getDefault();
                CtClass ctClass = cp.get(className.replace("/", "."));

                for (CtMethod method : ctClass.getDeclaredMethods()) {
                    if (method.hasAnnotation("org.springframework.web.bind.annotation.RequestMapping")) {
                        method.insertBefore("{ System.out.println(\"[API Hook] \" + \"" + method.getName() + "\"); }");
                    }
                }

                return ctClass.toBytecode();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return classfileBuffer;
    }
}
